package com.hanagent.interceptor;

import com.hanagent.model.Admins;
import com.hanagent.model.Agents;
import com.hanagent.model.Tokens;
import com.hanagent.utils.ConstantUtils;
import com.hanagent.utils.ResponseUtils;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation; 
import com.jfinal.core.Controller;

public class GlobalActionInterceptor implements Interceptor{

	public void intercept(Invocation inv) {  
		
		String keyActionString = inv.getActionKey().toLowerCase();
		
		if (keyActionString.contains("login") || keyActionString.contains("upload")) {
			inv.invoke();
		}else if (keyActionString.contains("private")) {
			try {
				String token = inv.getController().getHeader("token");
				Tokens findTokens = Tokens.dao.findFirst("select * from Tokens where token = ?", token);
				if (findTokens!=null) {
					if (findTokens.getTokenType()==2) {
						Admins admins = Admins.dao.findById(findTokens.getTokenUserId());
						if (admins!=null) {
							Agents agents = Agents.dao.findById(admins.getAgentId());
							if (agents!=null) {
								if (keyActionString.contains("getagentinfo")) { //所有管理员都可以获取
									
								}else if (admins.getType()==ConstantUtils.TypeAdminOrder && !keyActionString.contains("order") 
										&& !keyActionString.contains("getagentstock") && !keyActionString.contains("good")) { //订单管理员
									inv.getController().renderJson(ResponseUtils.sendResult(0, "", "你只可查看订单相关数据"));
									return;
								}else if (admins.getType()!=ConstantUtils.TypeAdminSuper && keyActionString.contains("admin")) {
									inv.getController().renderJson(ResponseUtils.sendResult(0, "", "只有全权管理员才可操作管理员模块"));
									return;
								}
								
								Controller contro = inv.getController();
								contro.setAttr("loginAgents", agents); 
								contro.setAttr("loginAdmins", admins); 
								inv.invoke();
							}else{
								inv.getController().renderJson(ResponseUtils.sendResult(0, "", "找不到用户相关的代理商"));
							}
						}else{
							inv.getController().renderJson(ResponseUtils.sendResult(0, "", "找不到用户相关的管理员，请重新登陆试试"));
						}
					}else{
						
					}
				}else{
					inv.getController().renderJson(ResponseUtils.sendResult(0, "", "请先登录"));
				}
			} catch (Exception e) {
				e.printStackTrace();
				inv.getController().renderJson(ResponseUtils.sendResult(0, "", "系统出错"));
			}
		}else{
			inv.invoke();
		}	 
	}
}
